<template>
    <div class="spot-manage-container">
      <!-- 搜索和操作区域 -->
      <div class="operation-area">
        <el-card shadow="hover">
          <div class="search-wrapper">
            <el-input
                v-model="searchQuery"
                placeholder="输入景点名称搜索"
                clearable
                class="search-input"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
  
            <el-select v-model="cityFilter" placeholder="城市筛选" clearable>
              <el-option label="全部" value="" />
              <el-option 
                v-for="city in cityList" 
                :key="city" 
                :label="city" 
                :value="city" 
              />
            </el-select>
  
            <el-select v-model="seasonFilter" placeholder="适宜季节" clearable>
              <el-option label="全部" value="" />
              <el-option label="春季" value="春" />
              <el-option label="夏季" value="夏" />
              <el-option label="秋季" value="秋" />
              <el-option label="冬季" value="冬" />
              <el-option label="四季皆宜" value="四季皆宜" />
            </el-select>
  
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>搜索
            </el-button>
  
            <el-button type="success" @click="handleAddSpot">
              <el-icon><Plus /></el-icon>新增景点
            </el-button>
          </div>
        </el-card>
      </div>
  
      <!-- 景点表格 -->
      <el-card shadow="hover" class="table-card">
        <el-table
            :data="filteredSpotList"
            border
            stripe
            style="width: 100%"
            v-loading="loading"
        >
          <el-table-column type="index" width="50" label="序号" />
  
          <el-table-column label="封面图" width="100">
            <template #default="scope">
              <el-image
                  :src="scope.row.coverImage ? `/images/${scope.row.coverImage}` : '/images/default.png'"
                  :preview-src-list="[scope.row.coverImage ? `/images/${scope.row.coverImage}` : '/images/default.png']"
                  fit="cover"
                  style="width: 80px; height: 60px; border-radius: 4px;"
              />
            </template>
          </el-table-column>
  
          <el-table-column prop="spotName" label="景点名称" width="200" />
  
          <el-table-column prop="englishName" label="英文名称" width="180">
            <template #default="scope">
              {{ scope.row.englishName || '未设置' }}
            </template>
          </el-table-column>
  
          <el-table-column prop="cityName" label="所在城市" width="120">
            <template #default="scope">
              {{ scope.row.cityName || '未设置' }}
            </template>
          </el-table-column>
  
          <el-table-column prop="averageCost" label="平均消费" width="100" sortable>
            <template #default="scope">
              {{ scope.row.averageCost }} 元
            </template>
          </el-table-column>
  
          <el-table-column prop="likes" label="点赞数" width="100" sortable />
  
          <el-table-column prop="score" label="评分" width="100" sortable>
  <template #default="scope">
    <span>{{ scope.row.score }}</span>
  </template>
</el-table-column>
  
          <el-table-column label="最佳季节" width="120">
            <template #default="scope">
              {{ getSeason(scope.row.season) }}
            </template>
          </el-table-column>
  
          <el-table-column prop="openTime" label="开放时间" width="150" />
  
          <el-table-column label="操作" fixed="right" width="220">
            <template #default="scope">
              <el-button
                  size="small"
                  @click="handleViewSpot(scope.row)"
                  type="primary"
                  link
              >
                查看
              </el-button>
  
              <el-button
                  size="small"
                  @click="handleEditSpot(scope.row)"
                  type="primary"
                  link
              >
                编辑
              </el-button>
  
              <el-button
                  size="small"
                  @click="handleDeleteSpot(scope.row)"
                  type="danger"
                  link
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalSpots"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
  
      <!-- 景点详情对话框 -->
      <el-dialog
          v-model="dialogVisible"
          :title="dialogType === 'add' ? '新增景点' : dialogType === 'edit' ? '编辑景点' : '景点详情'"
          width="700px"
      >
        <el-form
            ref="spotFormRef"
            :model="spotForm"
            :rules="spotFormRules"
            label-width="100px"
            :disabled="dialogType === 'view'"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="景点名称" prop="spotName">
                <el-input v-model="spotForm.spotName" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="英文名称" prop="englishName">
                <el-input v-model="spotForm.englishName" />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="所在城市" prop="cityName">
                <el-input v-model="spotForm.cityName" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="景点地址" prop="address">
                <el-input v-model="spotForm.address" />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="平均消费" prop="averageCost">
                <el-input-number v-model="spotForm.averageCost" :min="0" :precision="2" :step="10" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="评分" prop="score">
                <el-rate
                  v-model="spotForm.score"
                  show-score
                  :max="5"
                  :allow-half="true"
                  text-color="#ff9900"
                  score-template="{value}"
                />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="开放时间" prop="openTime">
                <el-input v-model="spotForm.openTime" placeholder="例如: 08:00-17:30" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="点赞数" prop="likes">
                <el-input-number v-model="spotForm.likes" :min="0" :step="1" />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-form-item label="旺季/最佳季节" prop="season">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-select v-model="seasonForm.peak" placeholder="旺季">
                  <el-option label="全年" value="全年" />
                  <el-option label="春季" value="春季" />
                  <el-option label="夏季" value="夏季" />
                  <el-option label="秋季" value="秋季" />
                  <el-option label="冬季" value="冬季" />
                  <el-option label="节假日" value="节假日" />
                  <el-option label="自定义" value="custom" />
                </el-select>
                <el-input 
                  v-if="seasonForm.peak === 'custom'" 
                  v-model="seasonForm.customPeak" 
                  placeholder="例如: 5-10月"
                  style="margin-top: 8px;"
                />
              </el-col>
              <el-col :span="12">
                <el-select v-model="seasonForm.best" placeholder="最佳季节">
                  <el-option label="四季皆宜" value="四季皆宜" />
                  <el-option label="春季" value="春季" />
                  <el-option label="夏季" value="夏季" />
                  <el-option label="秋季" value="秋季" />
                  <el-option label="冬季" value="冬季" />
                  <el-option label="春秋" value="春秋" />
                </el-select>
              </el-col>
            </el-row>
          </el-form-item>
  
          <el-form-item label="景点标签" prop="tags">
            <el-select
              v-model="spotForm.tags"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择或输入标签"
            >
              <el-option
                v-for="tag in availableTags"
                :key="tag.value"
                :label="tag.label"
                :value="tag.value"
              />
            </el-select>
          </el-form-item>
  
          <el-form-item label="封面图" prop="coverImage">
            <el-upload
                class="cover-uploader"
                action="/api/upload"
                :show-file-list="false"
                :on-success="handleCoverSuccess"
                :before-upload="beforeCoverUpload"
            >
              <img v-if="spotForm.coverImage" :src="`/images/${spotForm.coverImage}`" class="cover" />
              <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
  
          <el-form-item label="景点简介" prop="description">
            <el-input v-model="spotForm.description" type="textarea" rows="3" />
          </el-form-item>
        </el-form>
  
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button
                type="primary"
                @click="submitSpotForm"
                v-if="dialogType !== 'view'"
            >
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>
  
      <!-- 删除确认对话框 -->
      <el-dialog
          v-model="deleteDialogVisible"
          title="确认删除"
          width="400px"
      >
        <div class="delete-confirm">
          <el-icon class="warning-icon"><WarningFilled /></el-icon>
          <span>确定要删除景点 <strong>{{ selectedSpot.spotName }}</strong> 吗？此操作不可恢复！</span>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="deleteDialogVisible = false">取消</el-button>
            <el-button type="danger" @click="confirmDelete">确定删除</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { ref, reactive, computed, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Search, Plus, WarningFilled } from '@element-plus/icons-vue'
  import { selectAllSpots } from '@/api/spot'
  
  export default {
    name: 'SpotManagement',
    components: {
      Search,
      Plus,
      WarningFilled
    },
    setup() {
      // 状态和数据
      const loading = ref(false);
      const spotList = ref([]);
      const searchQuery = ref('');
      const cityFilter = ref('');
      const seasonFilter = ref('');
      const dialogVisible = ref(false);
      const dialogType = ref('view'); // 'view', 'add', 'edit'
      const deleteDialogVisible = ref(false);
      const selectedSpot = ref({});
      const currentPage = ref(1);
      const pageSize = ref(10);
      const totalSpots = ref(0);
      const cityList = ref([]);
  
      // 可用标签
      const availableTags = [
        { value: '1', label: '自然风光' },
        { value: '2', label: '山岳' },
        { value: '3', label: '文化古迹' },
        { value: '8', label: '生态景区' },
        { value: '10', label: '公园' },
        { value: '11', label: '历史遗迹' },
        { value: '13', label: '古城' },
        { value: '15', label: '宗教场所' },
        { value: '16', label: '革命圣地' },
        { value: '17', label: '长城' },
        { value: '18', label: '博物馆' },
        { value: '19', label: '古镇' },
        { value: '20', label: '遗址' },
        { value: '21', label: '园林' },
        { value: '27', label: '休闲娱乐' },
        { value: '31', label: '野生动物' },
        { value: '33', label: '农业观光' },
        { value: '34', label: '温泉' },
        { value: '35', label: '游乐园' },
        { value: '36', label: '观光景点' },
        { value: '38', label: '沙滩' },
        { value: '39', label: '海洋馆' },
        { value: '41', label: '主题园区' },
        { value: '42', label: '水上乐园' },
        { value: '50', label: '世界遗产' },
        { value: '51', label: '国家级景区' }
      ];
  
      // 季节表单
      const seasonForm = reactive({
        peak: '',
        customPeak: '',
        best: ''
      });
  
      // 景点表单
      const spotFormRef = ref(null);
      const spotForm = reactive({
        spotId: null,
        spotName: '',
        englishName: '',
        cityName: '',
        address: '',
        averageCost: 0,
        score: 5,
        likes: 0,
        openTime: '',
        season: '',
        tags: [],
        description: '',
        coverImage: '',
        title: '',
        visitorsCount: null,
        visitDuration: null
      });
  
      // 表单验证规则
      const spotFormRules = reactive({
        spotName: [
          { required: true, message: '请输入景点名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在2到50个字符之间', trigger: 'blur' }
        ],
        cityName: [
          { required: true, message: '请输入所在城市', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入景点地址', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入景点简介', trigger: 'blur' }
        ]
      });
  
      // 解析季节JSON字符串
      const getSeason = (seasonJSON) => {
        if (!seasonJSON) return '未设置';
        try {
          const seasonObj = JSON.parse(seasonJSON);
          return seasonObj["最佳季节"] || '未设置';
        } catch (e) {
          return '未设置';
        }
      };
  
      // 生成季节JSON
      const generateSeasonJSON = () => {
        const result = {};
        
        // 旺季
        if (seasonForm.peak === 'custom' && seasonForm.customPeak) {
          result["旺季"] = seasonForm.customPeak;
        } else if (seasonForm.peak && seasonForm.peak !== 'custom') {
          result["旺季"] = seasonForm.peak;
        }
        
        // 最佳季节
        if (seasonForm.best) {
          result["最佳季节"] = seasonForm.best;
        }
        
        return JSON.stringify(result);
      };
  
      // 解析标签字符串为数组
      const parseTagsStr = (tagsStr) => {
        if (!tagsStr) return [];
        try {
          // 从格式 "[1, 2, 3]" 解析为 ["1", "2", "3"]
          return JSON.parse(tagsStr.replace(/\s/g, ''));
        } catch (e) {
          return [];
        }
      };
  
      // 生成标签字符串
      const generateTagsStr = (tagsArray) => {
        return JSON.stringify(tagsArray);
      };
  
      // 根据过滤条件筛选景点
      const filteredSpotList = computed(() => {
        if (!spotList.value || !spotList.value.length) return [];
  
        return spotList.value.filter(spot => {
          // 搜索条件匹配
          const matchQuery = searchQuery.value
              ? (spot.spotName && spot.spotName.toLowerCase().includes(searchQuery.value.toLowerCase())) ||
                (spot.englishName && spot.englishName.toLowerCase().includes(searchQuery.value.toLowerCase())) ||
                (spot.address && spot.address.toLowerCase().includes(searchQuery.value.toLowerCase()))
              : true;
  
          // 城市筛选
          const matchCity = cityFilter.value
              ? spot.cityName === cityFilter.value
              : true;
  
          // 季节筛选
          let matchSeason = true;
          if (seasonFilter.value) {
            try {
              const seasonObj = JSON.parse(spot.season || '{}');
              matchSeason = seasonObj["最佳季节"] && seasonObj["最佳季节"].includes(seasonFilter.value);
            } catch (e) {
              matchSeason = false;
            }
          }
  
          return matchQuery && matchCity && matchSeason;
        });
      });
  
      // 分页后的数据
      const paginatedSpotList = computed(() => {
        const startIndex = (currentPage.value - 1) * pageSize.value;
        const endIndex = startIndex + pageSize.value;
        return filteredSpotList.value.slice(startIndex, endIndex);
      });
  
      // 获取景点列表
      const fetchSpotList = () => {
        loading.value = true;
        selectAllSpots()
          .then(res => {
            if (res.state === 0 && res.data) {
              spotList.value = res.data;
              totalSpots.value = res.data.length;
              
              // 提取所有不重复的城市名称
              const cities = new Set();
              res.data.forEach(spot => {
                if (spot.cityName) {
                  cities.add(spot.cityName);
                }
              });
              cityList.value = Array.from(cities);
            } else {
              ElMessage.error(res.message || '获取景点列表失败');
            }
          })
          .catch(error => {
            console.error('获取景点列表出错:', error);
            ElMessage.error('获取景点列表失败');
          })
          .finally(() => {
            loading.value = false;
          });
      };
  
      // 搜索景点
      const handleSearch = () => {
        currentPage.value = 1;
      };
  
      // 变更每页显示数量
      const handleSizeChange = (val) => {
        pageSize.value = val;
      };
  
      // 变更当前页码
      const handleCurrentChange = (val) => {
        currentPage.value = val;
      };
  
      // 查看景点
      const handleViewSpot = (row) => {
        selectedSpot.value = row;
        Object.assign(spotForm, JSON.parse(JSON.stringify(row)));
        
        // 解析季节
        try {
          const seasonObj = JSON.parse(row.season || '{}');
          seasonForm.peak = seasonObj["旺季"] || '';
          seasonForm.best = seasonObj["最佳季节"] || '';
          // 检查自定义旺季
          if (seasonForm.peak && !['全年', '春季', '夏季', '秋季', '冬季', '节假日'].includes(seasonForm.peak)) {
            seasonForm.customPeak = seasonForm.peak;
            seasonForm.peak = 'custom';
          }
        } catch (e) {
          seasonForm.peak = '';
          seasonForm.customPeak = '';
          seasonForm.best = '';
        }
        
        // 解析标签
        spotForm.tags = parseTagsStr(row.tags);
        
        dialogType.value = 'view';
        dialogVisible.value = true;
      };
  
      // 编辑景点
      const handleEditSpot = (row) => {
        selectedSpot.value = row;
        Object.assign(spotForm, JSON.parse(JSON.stringify(row)));
        
        // 解析季节
        try {
          const seasonObj = JSON.parse(row.season || '{}');
          seasonForm.peak = seasonObj["旺季"] || '';
          seasonForm.best = seasonObj["最佳季节"] || '';
          // 检查自定义旺季
          if (seasonForm.peak && !['全年', '春季', '夏季', '秋季', '冬季', '节假日'].includes(seasonForm.peak)) {
            seasonForm.customPeak = seasonForm.peak;
            seasonForm.peak = 'custom';
          }
        } catch (e) {
          seasonForm.peak = '';
          seasonForm.customPeak = '';
          seasonForm.best = '';
        }
        
        // 解析标签
        spotForm.tags = parseTagsStr(row.tags);
        
        dialogType.value = 'edit';
        dialogVisible.value = true;
      };
  
      // 添加景点
      const handleAddSpot = () => {
        // 重置表单
        Object.keys(spotForm).forEach(key => {
          if (key !== 'score' && key !== 'averageCost' && key !== 'likes') {
            spotForm[key] = '';
          }
        });
        spotForm.spotId = null;
        spotForm.score = 5;
        spotForm.averageCost = 0;
        spotForm.likes = 0;
        spotForm.tags = [];
        spotForm.title = '';
        
        // 重置季节表单
        seasonForm.peak = '';
        seasonForm.customPeak = '';
        seasonForm.best = '';
        
        dialogType.value = 'add';
        dialogVisible.value = true;
      };
  
      // 删除景点
      const handleDeleteSpot = (row) => {
        selectedSpot.value = row;
        deleteDialogVisible.value = true;
      };
  
      // 确认删除
      const confirmDelete = () => {
        loading.value = true;
        
        // 模拟API调用
        setTimeout(() => {
          // 从列表中移除
          const index = spotList.value.findIndex(item => item.spotId === selectedSpot.value.spotId);
          if (index !== -1) {
            spotList.value.splice(index, 1);
            totalSpots.value = spotList.value.length;
            ElMessage.success('删除成功');
          } else {
            ElMessage.error('删除失败：未找到景点');
          }
          
          deleteDialogVisible.value = false;
          loading.value = false;
        }, 500);
      };
  
      // 提交景点表单
      const submitSpotForm = () => {
        if (!spotFormRef.value) return;
  
        spotFormRef.value.validate((valid) => {
          if (valid) {
            // 处理季节信息
            spotForm.season = generateSeasonJSON();
            
            // 处理标签信息
            spotForm.tags = generateTagsStr(spotForm.tags);
            
            // 设置标题（如果为空）
            if (!spotForm.title) {
              spotForm.title = spotForm.spotName;
            }
            
            loading.value = true;
            
            // 模拟API调用
            setTimeout(() => {
              if (dialogType.value === 'add') {
                // 添加新景点
                const newSpot = { ...spotForm, spotId: Date.now() }; // 模拟生成ID
                spotList.value.unshift(newSpot);
                ElMessage.success('添加成功');
              } else {
                // 更新景点
                const index = spotList.value.findIndex(item => item.spotId === spotForm.spotId);
                if (index !== -1) {
                  spotList.value[index] = { ...spotForm };
                  ElMessage.success('更新成功');
                } else {
                  ElMessage.error('更新失败：未找到景点');
                }
              }
              
              dialogVisible.value = false;
              loading.value = false;
            }, 500);
          }
        });
      };
  
      // 封面图上传成功回调
      const handleCoverSuccess = (response) => {
        // 假设上传接口返回的格式是 { state: 0, data: { url: '图片地址' } }
        if (response.state === 0 && response.data) {
          spotForm.coverImage = response.data.url;
          ElMessage.success('封面图上传成功');
        } else {
          ElMessage.error('封面图上传失败');
        }
      };
  
      // 封面图上传前的验证
      const beforeCoverUpload = (file) => {
        const isJPG = file.type === 'image/jpeg';
        const isPNG = file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;
  
        if (!isJPG && !isPNG) {
          ElMessage.error('封面图只能是JPG或PNG格式!');
          return false;
        }
        if (!isLt2M) {
          ElMessage.error('封面图大小不能超过2MB!');
          return false;
        }
        return true;
      };
  
      // 生命周期钩子
      onMounted(() => {
        fetchSpotList();
      });
  
      return {
        loading,
        spotList,
        searchQuery,
        cityFilter,
        seasonFilter,
        dialogVisible,
        dialogType,
        deleteDialogVisible,
        selectedSpot,
        currentPage,
        pageSize,
        totalSpots,
        spotFormRef,
        spotForm,
        spotFormRules,
        seasonForm,
        availableTags,
        cityList,
        filteredSpotList,
        getSeason,
        handleSearch,
        handleSizeChange,
        handleCurrentChange,
        handleViewSpot,
        handleEditSpot,
        handleAddSpot,
        handleDeleteSpot,
        confirmDelete,
        submitSpotForm,
        handleCoverSuccess,
        beforeCoverUpload
      };
    }
  };
  </script>
  
  <style scoped>
  .spot-manage-container {
    padding: 20px;
  }
  
  .operation-area {
    margin-bottom: 20px;
  }
  
  .search-wrapper {
    display: flex;
    align-items: center;
    gap: 15px;
  }
  
  .search-input {
    width: 220px;
  }
  
  .table-card {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .cover-uploader {
    width: 120px;
    height: 90px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color 0.3s;
  }
  
  .cover-uploader:hover {
    border-color: #409EFF;
  }
  
  .cover-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 90px;
    line-height: 90px;
    text-align: center;
  }
  
  .cover {
    width: 120px;
    height: 90px;
    display: block;
    object-fit: cover;
  }
  
  .delete-confirm {
    display: flex;
    align-items: center;
    gap: 10px;
  }
  
  .warning-icon {
    font-size: 24px;
    color: #E6A23C;
  }
  </style>